package com.hyh.admin.config.websocket;

import com.hyh.ad.common.core.domain.model.SysUser;
import com.hyh.admin.config.websocket.context.SpringBeanContext;
import com.hyh.admin.domain.Messages;
import com.hyh.admin.service.IMessageService;
import com.hyh.admin.sys.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket 单聊服务端
 */
@ServerEndpoint("/singleChat/{username}")
@Component
public class WebSocketSingleServe implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(WebSocketSingleServe.class);

    // 记录当前在线的连接
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        // 将用户的session放入map中
        session.getUserProperties().put("username", username);
        sessionMap.put(username, session);
        log.info("用户：{}",session.getUserProperties().get("username"));
        log.info("用户：{} 连接成功，session：{}，总数：{}", username, session.getId(), sessionMap.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        try {
            sessionMap.values().remove(session);
            log.info("连接关闭，session：{}，总数：{}", session.getId(), sessionMap.size());
        } catch (Exception e) {
            log.error("连接关闭异常：{}", e.getMessage());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session fromSession) {
        // 假设消息格式为 "username:file:data"
        String[] parts = message.split(":", 3);
        if (parts.length == 3) {
            String targetUsername = parts[0].trim(); // 目标用户
            String type = parts[1].trim(); // 消息类型（text/file）
            String content = parts[2].trim(); // 消息内容

            log.info("收到消息：{}，类型：{}，内容：{}", targetUsername, type, content);
            // 根据类型处理消息
            if ("text".equals(type)) {
                // 发送文本消息
                sendMessageToUser(targetUsername, content, type);
            } else if ("image".equals(type)) {
                // 发送文件消息
                sendFileToUser(targetUsername, content, type);
            }else if ("file".equals(type)) {
                // 发送文件消息
                sendFileToUser(targetUsername, content, "file");
            }

            // 消息持久化
            String username = (String) fromSession.getUserProperties().get("username");
            saveMessage(username, targetUsername, content, type);
        }
    }



    /*
     * 消息持久化
     */
    private void saveMessage(String sendUsername, String targetUsername, String msg, String type) {
        // 保存消息
        try {
            IMessageService messageService = SpringBeanContext.getContext().getBean(IMessageService.class);
            ISysUserService sysUserService = SpringBeanContext.getContext().getBean(ISysUserService.class);
            SysUser targetUser = sysUserService.selectUserByUserName(targetUsername);
            Long targetUserId = targetUser.getId();
            SysUser sendUser = sysUserService.selectUserByUserName(sendUsername);
            Long userId = sendUser.getId();

            Messages messages = new Messages();
            messages.setSenderId(userId);
            messages.setReceiverId(targetUserId);
            messages.setContent(msg);
            messages.setMessageType(type); // 保存消息类型

            messageService.addMessage(messages);
            log.info("消息持久化成功");
        } catch (Exception e) {
            log.error("消息持久化失败：{}", e.getMessage());
        }
    }

    /*
     *  发送文件给用户
     */
    private void sendFileToUser(String targetUsername, String fileContent, String type) {
        Session targetSession = sessionMap.get(targetUsername);
        if (targetSession != null) {
            try {
                targetSession.getBasicRemote().sendText(type + "|" + fileContent); // 文件发送格式
                log.info("发送文件给用户：{}，发送成功", targetUsername);
            } catch (IOException e) {
                log.error("发送文件失败：{}", e.getMessage());
            }
        }
    }


    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误，session:{} ,错误信息：{}", session.getId(), error);
    }

    /**
     * 服务端发送消息给指定用户
     * @param username 目标用户
     * @param message 消息内容
     */
    public void sendMessageToUser(String username, String message, String type) {
        Session session = sessionMap.get(username);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(type + "|" + message);
                log.info("发送给用户：{}，内容：{}", username, message);
            } catch (IOException e) {
                log.error("发送消息失败：{}", e.getMessage());
            }
        } else {
            log.warn("用户：{} 不在线，无法发送消息", username);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("WebSocket服务端启动");
    }
}
